<template>
  <div class="train-plan-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h1>培训计划管理</h1>
        </div>
      </template>

      <!-- 新增培训计划按钮 -->
      <div class="header-actions">
        <el-button type="primary" @click="openCreateDialog">新增培训计划</el-button>
      </div>

      <!-- 培训计划列表 -->
      <el-table :data="trainPlans.content" border stripe style="width: 100%">
        <el-table-column prop="id" label="ID" />
        <el-table-column prop="title" label="计划名称" />
        <el-table-column prop="type" label="类型" />
        <el-table-column prop="startDate" label="开始日期" />
        <el-table-column prop="endDate" label="结束日期" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" :icon="Edit" @click.stop="openEditDialog(row)"></el-button>
            <el-button type="danger" :icon="Delete" @click.stop="deleteTrainPlan(row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
        :total="trainPlans.totalElements" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />

      <!-- 新增/编辑培训计划对话框 -->
      <el-dialog v-model="dialogVisible" :title="isEditMode ? '编辑培训计划' : '新增培训计划'">
        <el-form :model="form" label-width="120px">
          <el-row>
            <el-col :span="9">
              <el-form-item label="计划名称">
                <el-input v-model="form.title" />
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item label="类型">
                <el-select v-model="form.type" placeholder="请选择类型">
                  <el-option label="一级培养" value="first" />
                  <el-option label="二级培养" value="second" />
                  <el-option label="三级培养" value="third" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="开始日期">
                <el-date-picker v-model="form.startDate" type="date" placeholder="选择开始日期"
                  value-format="YYYY-MM-DD" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束日期">
                <el-date-picker v-model="form.endDate" type="date" placeholder="选择结束日期"
                  value-format="YYYY-MM-DD" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from '../axios';
import { ElMessage } from 'element-plus';
import { Delete, Edit } from '@element-plus/icons-vue';

// 培训计划列表
const trainPlans = ref({
  content: [], // 当前页的培训计划数据
  totalElements: 0, // 总数据量
});

// 表单数据
const form = ref({
  id: null,
  title: '',
  type: '',
  startDate: '',
  endDate: '',
});

// 对话框是否可见
const dialogVisible = ref(false);

// 是否为编辑模式
const isEditMode = ref(false);

// 分页相关状态
const currentPage = ref(1); // 当前页码（从 1 开始）
const pageSize = ref(5); // 每页大小

// 获取培训计划列表
const fetchTrainPlans = async (page = 1, size = 5) => {
  try {
    const response = await axios.get('/train-plans', {
      params: { page: page, size },
    });
    trainPlans.value = response.data;
  } catch (error) {
    ElMessage.error('获取培训计划列表失败');
  }
};

// 打开新增对话框
const openCreateDialog = () => {
  isEditMode.value = false; // 设置为新增模式
  form.value = { id: null, title: '', type: '', startDate: '', endDate: '' }; // 清空表单
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (row) => {
  isEditMode.value = true; // 设置为编辑模式
  form.value = { ...row }; // 填充表单
  dialogVisible.value = true;
};

// 表单验证
const validateForm = () => {
  if (!form.value.title || !form.value.type || !form.value.startDate || !form.value.endDate) {
    ElMessage.error('请填写所有必填字段');
    return false;
  }
  if (form.value.startDate > form.value.endDate) {
    ElMessage.error('开始日期不能晚于结束日期');
    return false;
  }
  return true;
};

// 提交表单（新增或更新）
const submitForm = async () => {
  if (!validateForm()) {
    return; // 如果表单验证失败，直接返回
  }
  console.log('提交的表单数据:', form.value); // 打印表单数据
  try {
    if (isEditMode.value) {
      // 更新培训计划
      const response = await axios.put(`/train-plans/${form.value.id}`, form.value);
      const index = trainPlans.value.content.findIndex((plan) => plan.id === form.value.id);
      if (index !== -1) {
        trainPlans.value.content.splice(index, 1, response.data);
      }
      ElMessage.success('培训计划更新成功');
    } else {
      // 新增培训计划
      const response = await axios.post('/train-plans', form.value);
      trainPlans.value.content.push(response.data);
      ElMessage.success('培训计划新增成功');
    }
    dialogVisible.value = false; // 关闭对话框
    fetchTrainPlans(currentPage.value, pageSize.value); // 刷新当前页的培训计划列表
  } catch (error) {
    ElMessage.error(error.response?.data || '操作失败');
  }
};

// 删除培训计划
const deleteTrainPlan = async (id) => {
  try {
    await axios.delete(`/train-plans/${id}`);
    trainPlans.value.content = trainPlans.value.content.filter((plan) => plan.id !== id);
    ElMessage.success('培训计划删除成功');
  } catch (error) {
    ElMessage.error('培训计划删除失败');
  }
};

// 处理每页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchTrainPlans(1, size); // 每页大小变化时，加载第一页数据
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchTrainPlans(page, pageSize.value); // 加载对应页的数据
};

// 初始化时加载第一页数据
onMounted(() => {
  fetchTrainPlans();
});
</script>

<style scoped>
.train-plan-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.card-header {
  text-align: center;
}

.header-actions {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
::v-deep.el-table th,
::v-deep.el-table td {
  height: 40px;
  line-height: 40px;
  text-align: center;
}
</style>